package com.example.floatingwindow.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.Nullable;

import com.example.floatingwindow.R;

public class LineView extends View {

    private Paint mPaintLine;
    private Paint mPaintBackLine;
    private float process;
    private float width;

    public LineView(Context context) {
        super(context);
        init();
    }

    public LineView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        mPaintLine = new Paint();
        mPaintLine.setColor(getResources().getColor(R.color.gray));
        mPaintLine.setStyle(Paint.Style.STROKE);
        mPaintLine.setAntiAlias(true);
        mPaintLine.setStrokeWidth(20);

        mPaintBackLine = new Paint();
        mPaintBackLine.setColor(getResources().getColor(R.color.blue));
        mPaintBackLine.setStyle(Paint.Style.STROKE);
        mPaintBackLine.setAntiAlias(true);
        mPaintBackLine.setStrokeWidth(20);
    }

    public void start() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, width);
        valueAnimator.setDuration(2000);
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(animation -> {
            process = (float) animation.getAnimatedValue();
            invalidate();
        });
        valueAnimator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        width = getWidth();
        int percent = (int) (process / width * 100);
        float stopX = percent * width / 100;
        canvas.drawLine(0, 0, width, 0, mPaintLine);
        canvas.drawLine(0, 0, stopX, 0, mPaintBackLine);
    }
}
